<template>
  <div>
    <vxe-toolbar style="height: 100px;">
      <template #buttons>
        <el-row style="margin-bottom: 20px;">
          <el-col :span="6">
            <el-input v-model="searchForm.name" size="small" placeholder="请输入房间号" style="width: 60%;"></el-input>
          </el-col>
          <el-col :span="5">
            <el-select v-model="searchForm.genderId" size="small" filterable clearable placeholder="请选择性别">
              <el-option :label="item" :value="key" v-for="(item,key,index) in dict_gender" :key="index">
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="5">
            <el-select v-model="searchForm.dormStandardId" size="small" filterable clearable placeholder="请选择宿舍规格">
              <el-option :label="item" :value="key" v-for="(item,key,index) in dict_dormStandard" :key="index">
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="5">
            <el-select v-model="searchForm.empId" size="small" filterable clearable placeholder="请选择宿舍管理员">
              <el-option :label="item" :value="key" v-for="(item,key,index) in dict_emp" :key="index">
              </el-option>
            </el-select>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6" style="display: flex;">
            <el-button type="success" icon="el-icon-plus" size="small" @click="insertEvent">新增</el-button>
            <el-button type="success" icon="el-icon-printer" size="small" @click="exportData">导出</el-button>
            <el-button type="success" icon="el-icon-printer" size="small" @click="printEvent">打印</el-button>
          </el-col>
          <el-col :span="9">
            <el-select v-model="searchForm.dormStatusId" size="small" filterable clearable placeholder="请选择房间状态">
              <el-option :label="item" :value="key" v-for="(item,key,index) in dict_dormStatus" :key="index">
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="5" style="display: flex;">
            <el-button type="success" size="small" icon="el-icon-s-promotion" @click="searchSubmit"
              style="margin: 0 10px;">
              搜索</el-button>
            <vxe-button @click="clearTableFilter" status="warning" icon="el-icon-refresh-right"> 清空</vxe-button>
          </el-col>
          <el-col :span="4">
            <vxe-input style="float: right;" v-model.trim.lazy="filterName" type="search" placeholder="快捷检索"
              @input="searchEvent"></vxe-input>
          </el-col>
        </el-row>
      </template>
    </vxe-toolbar>
    <vxe-table resizable ref="XTable" show-overflow border max-height="800" stripe highlight-hover-row highlight-current-row
      :loading="loading" :data="dataList" @sort-change="sortChange">
      <vxe-table-column field="name" title="房间号" sortable></vxe-table-column>
      <vxe-table-column field="gender" title="性别" sortable></vxe-table-column>
      <vxe-table-column field="dormStandard" title="宿舍规格" sortable></vxe-table-column>
      <vxe-table-column field="location" title="位置" sortable></vxe-table-column>
      <vxe-table-column field="emp" title="宿舍管理员" sortable></vxe-table-column>
      <vxe-table-column field="dormOfficial" title="舍长" sortable></vxe-table-column>
      <vxe-table-column field="maxPlayerNum" title="最大人数" sortable></vxe-table-column>
      <vxe-table-column field="currentPlayerNum" title="当前人数" sortable></vxe-table-column>
      <vxe-table-column field="dormStatus" title="房间状态" sortable></vxe-table-column>
      <vxe-table-column field="" title="操作" width="110">
        <template #default="{ row,rowIndex }">
          <el-button @click="editEvent(row,rowIndex)" type="success" size="medium" icon="el-icon-edit" circle></el-button>
          <el-button @click="deleteEvent(row)" type="danger" size="medium" icon="el-icon-delete" circle></el-button>
        </template>
      </vxe-table-column>
    </vxe-table>
    <vxe-pager :loading="loading" :current-page="page.currentPage" :page-size="page.pageSize" :total="page.totalResult"
      :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']" @page-change="handlePageChange">
    </vxe-pager>
    <vxe-modal v-model="insertModal" title="宿舍管理">
      <template #default>
        <el-form inline-message ref="insertForm" :rules="rules" :model="insertForm" label-width="110px">
          <el-form-item label="房间号" prop="name">
            <el-input v-model="insertForm.name"></el-input>
          </el-form-item>
          <el-form-item label="性别" prop="genderId">
            <el-select v-model="insertForm.genderId" filterable clearable style="width: 100%;" placeholder="请选择">
              <el-option :label="item" :value="key" v-for="(item,key,index) in dict_gender" :key="index"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="宿舍规格" prop="dormStandardId">
            <el-select v-model="insertForm.dormStandardId" filterable clearable style="width: 100%;" placeholder="请选择">
              <el-option :label="item" :value="key" v-for="(item,key,index) in dict_dormStandard" :key="index">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="位置" prop="location">
            <el-input v-model="insertForm.location"></el-input>
          </el-form-item>
          <el-form-item label="宿舍管理员" prop="empId">
            <el-select v-model="insertForm.empId" filterable clearable style="width: 100%;" placeholder="请选择">
              <el-option :label="item" :value="key" v-for="(item,key,index) in dict_emp" :key="index"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="最大人数" prop="maxPlayerNum">
            <el-input v-model.number="insertForm.maxPlayerNum" type="number"></el-input>
          </el-form-item>
          <el-form-item label="房间状态" prop="dormStatusId">
            <el-select v-model="insertForm.dormStatusId" filterable clearable style="width: 100%;" placeholder="请选择">
              <el-option :label="item" :value="key" v-for="(item,key,index) in dict_dormStatus" :key="index"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="warning" size="small" @click="insertModal = false">取消</el-button>
            <el-button type="success" size="small" icon="el-icon-s-promotion" @click="insertSave">保存</el-button>
          </el-form-item>
        </el-form>
      </template>
    </vxe-modal>
  </div>
</template>
<script>
  import {
    dorm_all,
    dorm_insert,
    dorm_update,
    dorm_delete,
    dorm_select,
  } from '@/api/person.js'
  import {
    currentRoleEmployee,
    dorm_standard,
    currentRolePlayer
  } from '@/api/dict.js'
  import sportChangesportItem from '@/components/sport2sportItem/sport2sportItem.vue'
  export default {
    components: {
      sportChangesportItem
    },
    data() {
      return {
        doubleDate: '',
        pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
        defaultDataList: [],
        dataList: [],
        page: {
          currentPage: 1,
          pageSize: 10,
          totalResult: 0
        },
        loading: false,
        filterName: '',
        insertModal: false,
        dict_emp: {},
        dict_player: {},
        dict_gender: {1:'男',2:'女'},
        dict_dormStandard: {},
        dict_dormStatus: {
          1:'在用',
          2:'维修',
          3:'封锁'
        },
        insertForm: {
          name: '',
          genderId: '',
          dormStandardId: '',
          empId: '',
          dormStatusId: '',
          location: '',
          maxPlayerNum: '',
        },
        searchForm: {
          name: '',
          genderId: '',
          dormStandardId: '',
          empId: '',
          dormStatusId: '',
        },
        sportItemData: [],
        rules: {
          pId: [{
            required: true,
            message: '这是必填项',
            trigger: 'blur'
          }, ],
        },
        isInsert: true,
        dormId: '',
        pid: '',
        sportChangesportItemData: {},
        currentIndex: null,
        search: false,
      }
    },
    created() {
      this.dorm_all()
    },
    computed: {
      openDateValid() {
        if (this.insertForm.openDate && this.insertForm.closeDate) {
          if (this.insertForm.openDate > this.insertForm.closeDate) {
            this.$message.error('开始时间必须小于结束时间！')
            return false
          } else {
            return true
          }
        } else {
          return true
        }
      }
    },
    watch: {
      filterName(val) {
        if(!val){
          this.page = {
          currentPage: 1,
          pageSize: 10,
          totalResult: 0,
          }
          this.search = false
          this.findList()
        }
      }
    },
    methods: {
      searchSelectDataChange({
        sportId,
        person,
        playerId
      }) {
        this.searchForm.sportId = sportId
        this.searchForm.coachId = person
        this.searchForm.playerId = playerId
      },
      insertSelectDataChange({
        sportId,
        sportItemId,
        person,
        playerId
      }) {
        this.insertForm.sportId = sportId
        this.insertForm.sportItemId = sportItemId
        this.insertForm.playerId = playerId
        this.insertForm.coachId = person
      },
      clearTableFilter() {
        this.searchForm = {
          name: '',
          genderId: '',
          dormStandardId: '',
          empId: '',
          dormStatusId: '',
        }
        this.doubleDate = ''
        this.sportChangesportItemData = {}
        this.dorm_all()
      },
      searchSubmit() {
        let data = {}
        if (this.searchForm.name) data.name = this.searchForm.name
        if (this.searchForm.genderId) data.genderId = this.searchForm.genderId
        if (this.searchForm.dormStandardId) data.dormStandardId = this.searchForm.dormStandardId
        if (this.searchForm.empId) data.empId = this.searchForm.empId
        if (this.searchForm.dormStatusId) data.dormStatusId = this.searchForm.dormStatusId
        dorm_select(data).then(res => {
          if (res.code === 200 && res.data.length != 0) {
            this.page = {
              currentPage: 1,
              pageSize: 10,
              totalResult: 0
            }
            this.init_data(res.data)
          } else {
            this.defaultDataList = []
          }
        }).then(() => {
          this.findList()
        })
      },
      deleteEvent(row) {
        this.$confirm('此操作将永久删除该条记录, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          dorm_delete({
            dormId: row.dormId
          }).then(res => {
            if (res.code === 200) {
              this.defaultDataList.forEach((item,index)=>{
              	if(item.dormId == row.dormId){
              	  this.defaultDataList.splice(index,1)
              	}
              })
              this.init_data(this.defaultDataList)
              this.findList()
              this.$message.success('删除成功！')
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      checkedEvent(row) {
        this.$confirm('注意：审核过之后，该条数据将不能再被修改', '审核', {
          confirmButtonText: '√通过审核',
          cancelButtonText: '放弃审核',
          type: 'warning'
        }).then(() => {
          player_profile_check({
            dormId: row.dormId
          }).then(res => {
            if (res.code === 200) {
              this.dorm_all()
              this.$message.success('已审核.！')
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消审核.'
          });
        });
      },
      editEvent(row,rowIndex) {
        this.currentIndex = rowIndex
        if (row.checkUserId!=0) {
          this.$message.warning('已经审核过的数据不能修改')
        } else {
          this.dormId = row.dormId
          this.insertForm.name = row.name
          this.insertForm.genderId = row.genderId==0?'':row.genderId+''
          this.insertForm.dormStandardId = row.dormStandardId==0?'':row.dormStandardId+''
          this.insertForm.location = row.location
          this.insertForm.empId = row.empId==0?'':row.empId+''
          this.insertForm.maxPlayerNum = row.maxPlayerNum
          this.insertForm.dormStatusId = row.dormStatusId==0?'':row.dormStatusId+''
          this.isInsert = false
          this.insertModal = true
        }
      },
      insertSave() {
        this.$refs.insertForm.validate((valid) => {
          if (valid && this.openDateValid) {
            let data = {}
            if (this.insertForm.name) data.name = this.insertForm.name
            if (this.insertForm.genderId) data.genderId = this.insertForm.genderId
            if (this.insertForm.dormStandardId) data.dormStandardId = this.insertForm.dormStandardId
            if (this.insertForm.location) data.location = this.insertForm.location
            if (this.insertForm.empId) data.empId = this.insertForm.empId
            if (this.insertForm.maxPlayerNum) data.maxPlayerNum = this.insertForm.maxPlayerNum
            if (this.insertForm.dormStatusId) data.dormStatusId = this.insertForm.dormStatusId
            if (this.isInsert) {
              dorm_insert(data).then(res => {
                if (res.code === 200) {
                  this.dataList.unshift(res.data)
                  this.defaultDataList.push(res.data)
                  this.init_data(this.defaultDataList)
                  this.page.totalResult+=1
                  this.$refs.XTable.setCurrentRow(this.dataList[0])
                  this.$message.success('保存成功')
                  this.insertSuccess = true
                  this.insertModal = false
                } else {
                  this.$message.error(res.message)
                }
              })
            } else {
              data.dormId = this.dormId
              dorm_update(data).then(res => {
                if (res.code === 200) {
                  Object.assign(this.dataList[this.currentIndex],res.data)
                  this.defaultDataList.forEach(item=>{
                  	if(res.data.dormId==item.dormId){
                  	  Object.assign(item,res.data)
                  	}
                  })
                  this.init_data(this.defaultDataList)
                  this.$message.success('修改成功')
                  this.insertModal = false
                } else {
                  this.$message.error(res.message)
                }
              })
            }
          } else {
            return false;
          }
        })
      },
      insertEvent() {
        this.insertForm = {
          dorm: '',
          alias: '',
          genderId: '',
          dormStandarId: '',
          location: '',
          empId: '',
          dormOfficial: '',
          maxPlayerNum: '',
          currentPlayerNum: '',
          dormStatusId: '',

        }
        this.sportChangesportItemData = {}
        this.isInsert = true
        this.insertModal = true
      },
      exportData() {
        this.$refs.XTable.exportData({
          filename: this.$store.state.user.org+'宿舍管理',
          type: 'csv',
          data: this.search?this.dataList:this.defaultDataList
        })
      },
      printEvent() {
        let topHtml = '<h2>宿舍管理</h2>'
        this.searchEvent()
        setTimeout(() => {
          this.$refs.XTable.print({
            sheetName: '宿舍管理',
            beforePrintMethod: ({
              content
            }) => {
              return topHtml + content
            }
          })
        }, 1000)
      },
      searchEvent() {
        const filterName = this.$XEUtils.toValueString(this.filterName).trim().toLowerCase()
        if (filterName) {
          const filterRE = filterName
          const searchProps = this.searchProps
          const rest = this.defaultDataList.filter(item => searchProps.some(key => this.$XEUtils.toValueString(item[
            key]).toLowerCase().indexOf(filterName) > -1))
          this.dataList = rest.map(row => {
            const item = Object.assign({}, row)
            searchProps.forEach(key => {
              item[key] = this.$XEUtils.toValueString(item[key]).replace(filterRE, match => match)
            })
            return item
          })
          this.page = {
            currentPage: 1,
            pageSize: this.dataList.length,
            totalResult: this.dataList.length
          }
          this.search = true
        } else {
          this.dataList = this.defaultDataList
     }
      },
      dorm_all() {
        this.init_dict().then(() => {
          dorm_all().then(res => {
            if (res.code === 200 && res.data.length != 0) {
              this.init_data(res.data)
            } else {
              this.defaultDataList = []
            }
          }).then(() => {
            this.findList()
          })
        })
      },
      init_data(data) {
        if(data.length==0) return
        data.forEach(item => {
          item.gender = this.dict_gender[item.genderId]
          item.dormStandard = this.dict_dormStandard[item.dormStandardId]
          item.emp = this.dict_emp[item.empId]
          if(this.dict_player[item.dormOfficial]){
            item.dormOfficial = this.dict_player[item.dormOfficial]
          }else{
            item.dormOfficial = '未设置'
          }
          item.dormStatus = this.dict_dormStatus[item.dormStatusId]
        })
        this.searchProps = Object.keys(data[0])
        this.defaultDataList = data
      },
      init_dict() {
        return new Promise((resolve, reject) => {
          dorm_standard().then(res=>{
            this.dict_dormStandard = res
          })
          currentRolePlayer().then(res=>{
            this.dict_player = res
          })
          currentRoleEmployee().then(res => {
            this.dict_emp = res
            resolve()
          })
        })
      },
      handlePageChange({
        currentPage,
        pageSize
      }) {
        this.page.currentPage = currentPage
        this.page.pageSize = pageSize
        this.findList()
      },
      sortChange() {
        if(!this.search){
          this.page.pageSize = this.defaultDataList.length
          this.findList()
        }else{
          this.page.pageSize = this.dataList.length
        }
      },
      findList() {
        this.loading = true
        setTimeout(() => {
          if(this.insertSuccess){
            this.page.totalResult = this.defaultDataList.length
            this.page.currentPage = Math.ceil(this.page.totalResult/this.page.pageSize)
            this.dataList = this.defaultDataList.slice((this.page.currentPage - 1) * this.page
              .pageSize, this.page.currentPage * this.page.pageSize)
            this.$refs.XTable.setCurrentRow(this.dataList[this.dataList.length-1])
            this.insertSuccess = false
          }else{
            this.page.totalResult = this.defaultDataList.length
            this.dataList = this.defaultDataList.slice((this.page.currentPage - 1) * this.page
              .pageSize, this.page.currentPage * this.page.pageSize)
          }
          this.loading = false
        }, 300)
      },
    }
  }
</script>

<style lang="scss" scoped>

</style>
